package com.ruoyi.system.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.system.service.IChatHistoryService;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/chatHistory")
public class ChatHistoryController {

    @Autowired
    private IChatHistoryService iChatHistoryService;

    @GetMapping("/getChatHistory")
    public AjaxResult getChatHistory(@RequestParam String userId) {
        if(userId == null || userId.isEmpty()) {
            return AjaxResult.error("用户ID不能为空");
        }
        return AjaxResult.success(iChatHistoryService.selectChatHistoryByUserId(userId));
    }


    @PostMapping("/addChatHistory")
    public AjaxResult addChatHistory(@RequestBody(required = false) Map<String, String> requestBody) {
        // 检查请求体是否存在
        if (requestBody == null) {
            return AjaxResult.error("请求体不能为空");
        }

        // 从请求体中获取参数
        String userId = requestBody.get("userId");
        String title = requestBody.get("title");

        // 参数校验
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error("用户ID不能为空");
        }
        if (StringUtils.isEmpty(title)) {
            return AjaxResult.error("对话标题不能为空");
        }

        try {
            String chatId = iChatHistoryService.addChatHistory(userId, title);
            Map<String, Object> data = new HashMap<>();
            data.put("chatId", chatId);
            return AjaxResult.success("操作成功", data);
        } catch (Exception e) {
            return AjaxResult.error("添加对话失败: " + e.getMessage());
        }
    }

    @PostMapping("/deleteChatHistory")
    public AjaxResult deleteChatHistory(@RequestBody Map<String, String> requestBody) {
        String chatId = requestBody.get("chatId");

        // 参数校验
        if (StringUtils.isEmpty(chatId)) {
            return AjaxResult.error("对话ID不能为空");
        }

        try {
            int result = iChatHistoryService.deleteChatHistory(chatId);
            if (result > 0) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("对话不存在或删除失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }
}
